import React, { useState, useEffect, useCallback } from "react";
import { DictDataAPI, DictTypeAPI } from "@/api/dictionary";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import {
  Plus,
  Edit,
  Trash2,
  Save,
  Search,
  Filter,
  RefreshCw,
  AlertCircle,
  ChevronLeft,
  ChevronRight,
  MoreHorizontal,
} from "lucide-react";
import { useToast } from "@/components/ui/use-toast";

// 生成带时间戳的字典编码（确保唯一性）
const generateDictCode = () => {
  return `${Date.now()}`;
};

const DictionaryDataManager = () => {
  // 状态管理
  const [dictDataList, setDictDataList] = useState([]);
  const [dictTypes, setDictTypes] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalItems, setTotalItems] = useState(0);
  const [searchTerm, setSearchTerm] = useState("");
  const [typeFilter, setTypeFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentData, setCurrentData] = useState(null);
  const [formData, setFormData] = useState({
    dictType: "",
    status: "0",
    dictCode: "", // 保留字段但不在表单显示
    dictLabel: "",
    dictValue: "",
    isDefault: "0",
  });
  const [formErrors, setFormErrors] = useState({});
  const { toast } = useToast();

  // 计算总页数
  const totalPages = Math.ceil(totalItems / pageSize) || 1;

  // 加载字典类型列表
  const loadDictTypes = useCallback(async () => {
    try {
      const response = await DictTypeAPI.getList();
      setDictTypes(response.rows || []);
    } catch (error) {
      console.error("加载字典类型失败:", error);
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "无法加载字典类型数据，请稍后重试",
      });
    }
  }, [toast]);

  // 加载字典数据列表
  const loadDictData = useCallback(async () => {
    setIsLoading(true);
    try {
      const params = {
        page: currentPage,
        size: pageSize,
        ...(searchTerm && { keyword: searchTerm }),
        ...(typeFilter && { dictType: typeFilter }),
        ...(statusFilter !== "all" && { status: statusFilter }),
      };

      const response = await DictDataAPI.getList(params);
      setDictDataList(response.rows || []);
      setTotalItems(response.total || 0);

      // 边界处理：当前页超过总页数时回退
      if (currentPage > totalPages && totalPages > 0) {
        setCurrentPage(totalPages);
      }
    } catch (error) {
      console.error("加载字典数据失败:", error);
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "无法加载字典数据，请稍后重试",
      });
    } finally {
      setIsLoading(false);
    }
  }, [
    currentPage,
    pageSize,
    searchTerm,
    typeFilter,
    statusFilter,
    totalPages,
    toast,
  ]);

  // 统一监听筛选条件变化
  useEffect(() => {
    const timer = setTimeout(() => {
      loadDictData();
    }, 0);
    return () => clearTimeout(timer);
  }, [currentPage, pageSize, searchTerm, typeFilter, statusFilter, loadDictData]);

  // 初始加载
  useEffect(() => {
    const initLoad = async () => {
      await loadDictTypes();
    };
    initLoad();
  }, [loadDictTypes]);

  // 表单输入变化处理
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    if (formErrors[name]) {
      setFormErrors((prev) => ({ ...prev, [name]: null }));
    }
  };

  // 选择框变化处理
  const handleSelectChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (formErrors[field]) {
      setFormErrors((prev) => ({ ...prev, [field]: null }));
    }
  };

  // 状态筛选变化处理
  const handleStatusFilterChange = (value) => {
    setStatusFilter(value);
    setCurrentPage(1);
  };

  // 字典类型筛选变化处理
  const handleTypeFilterChange = (value) => {
    const newTypeFilter = value === "all" ? "" : value;
    setTypeFilter(newTypeFilter);
    setCurrentPage(1);
  };

  // 表单验证（移除字典编码验证）
  const validateForm = () => {
    const errors = {};
    if (!formData.dictType) errors.dictType = "请选择字典类型";
    if (!formData.dictLabel) errors.dictLabel = "请输入字典标签";
    if (!formData.dictValue.trim()) errors.dictValue = "请输入字典键值";
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 打开新增模态框（自动生成字典编码）
  const handleAdd = () => {
    setCurrentData(null);
    setFormData({
      dictType: typeFilter || "",
      status: "0",
      dictCode: generateDictCode(), // 自动生成带时间戳的编码
      dictLabel: "",
      dictValue: "",
      isDefault: "0",
    });
    setFormErrors({});
    setIsModalOpen(true);
  };

  // 打开编辑模态框（保留原字典编码）
  const handleEdit = (data) => {
    setCurrentData(data);
    setFormData({
      dictType: data.dictType || "",
      status: (data.status ?? "0").toString(),
      dictCode: data.dictCode || "", // 编辑时沿用原编码
      dictLabel: data.dictLabel || "",
      dictValue: data.dictValue || "",
      isDefault: (data.isDefault ?? "0").toString(),
    });
    setFormErrors({});
    setIsModalOpen(true);
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!validateForm()) return;
    try {
      const submitData = { ...formData };

      if (currentData) {
        await DictDataAPI.update(currentData.dictCode, submitData);
        toast({
          title: "更新成功",
          description: "字典数据已成功更新",
        });
      } else {
        await DictDataAPI.create(submitData);
        toast({
          title: "创建成功",
          description: "新字典数据已成功创建",
        });
      }
      setIsModalOpen(false);
      loadDictData();
    } catch (error) {
      console.error("提交字典数据失败:", error);
      toast({
        variant: "destructive",
        title: "操作失败",
        description: error.message || "处理请求时发生错误，请稍后重试",
      });
    }
  };

  // 删除字典数据
  const handleDelete = async (dictCode) => {
    if (!window.confirm("确定要删除此字典数据吗？此操作无法撤销。")) {
      return;
    }

    try {
      await DictDataAPI.delete(dictCode);
      toast({
        title: "删除成功",
        description: "字典数据已成功删除",
      });

      const shouldResetPage = dictDataList.length === 1 && currentPage > 1;
      if (shouldResetPage) {
        setCurrentPage((prev) => prev - 1);
      } else {
        loadDictData();
      }
    } catch (error) {
      console.error("删除字典数据失败:", error);
      toast({
        variant: "destructive",
        title: "删除失败",
        description: error.message || "删除字典数据时发生错误，请稍后重试",
      });
    }
  };

  // 搜索处理
  const handleSearch = (e) => {
    e?.preventDefault();
    setCurrentPage(1);
  };

  // 渲染状态标签
  const renderStatusBadge = (status) => {
    const statusMap = {
      0: { label: "正常", class: "bg-green-100 text-green-800" },
      1: { label: "停用", class: "bg-red-100 text-red-800" },
    };
    const { label, class: badgeClass } = statusMap[status] || {
      label: "未知",
      class: "bg-gray-100 text-gray-800",
    };
    return (
      <Badge className={`${badgeClass} hover:${badgeClass}`}>{label}</Badge>
    );
  };

  // 渲染是否默认标签
  const renderIsDefault = (isDefault) => {
    return isDefault === "1" ? (
      <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-100">是</Badge>
    ) : (
      <Badge className="bg-gray-100 text-gray-800 hover:bg-gray-100">否</Badge>
    );
  };

  // 获取字典类型名称
  const getDictTypeName = (type) => {
    const foundType = dictTypes.find((item) => item.dictType === type);
    return foundType ? foundType.dictName : type;
  };

  // 处理每页显示数量变化
  const handleItemsPerPageChange = (count) => {
    setPageSize(count);
    setCurrentPage(1);
  };

  // 处理页码变化
  const handlePageChange = (pageNum) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  // 渲染分页组件
  const renderPagination = () => {
    const startIndex = Math.max(1, (currentPage - 1) * pageSize + 1);
    const endIndex = Math.min(currentPage * pageSize, totalItems);

    if (totalItems === 0) return null;

    return (
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
        <div className="text-sm text-gray-500">
          共 {totalItems} 条数据，显示 {startIndex} 到 {endIndex} 条
        </div>
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm" className="h-8 min-w-[120px]">
                每页 {pageSize} 条
                <MoreHorizontal className="ml-2 h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {[5, 10, 20, 50].map((count) => (
                <DropdownMenuItem
                  key={`page-size-${count}`}
                  onClick={() => handleItemsPerPageChange(count)}
                  className={pageSize === count ? "bg-primary/10" : ""}
                >
                  {count} 条/页
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
              aria-disabled={currentPage === 1}
            >
              <ChevronLeft className="h-4 w-4" />
              <span className="sr-only">上一页</span>
            </Button>

            {/* 生成页码 */}
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNum;
              if (totalPages <= 5) {
                pageNum = i + 1;
              } else if (currentPage <= 3) {
                pageNum = i + 1;
              } else if (currentPage >= totalPages - 2) {
                pageNum = totalPages - 4 + i;
              } else {
                pageNum = currentPage - 2 + i;
              }
              return (
                <Button
                  key={`page-num-${pageNum}`}
                  variant={currentPage === pageNum ? "default" : "outline"}
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => handlePageChange(pageNum)}
                  aria-current={currentPage === pageNum ? "page" : undefined}
                >
                  {pageNum}
                </Button>
              );
            })}

            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
              aria-disabled={currentPage === totalPages}
            >
              <ChevronRight className="h-4 w-4" />
              <span className="sr-only">下一页</span>
            </Button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="space-y-4">
      {/* 头部操作区 */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h3 className="text-lg font-semibold">字典数据管理</h3>
          <p className="text-sm text-gray-500">管理各类型字典的具体数据条目</p>
        </div>

        <div className="flex flex-wrap items-center gap-3 w-full sm:w-auto">
          {/* 字典类型筛选 */}
          <Select
            value={typeFilter || "all"}
            onValueChange={handleTypeFilterChange}
          >
            <SelectTrigger className="w-full sm:w-[180px]">
              <SelectValue placeholder="选择字典类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem key="all-types" value="all">
                全部类型
              </SelectItem>
              {dictTypes.map((type) => (
                <SelectItem
                  key={`filter-type-${type.dictType}`}
                  value={type.dictType}
                >
                  {type.dictName}（{type.dictType}）
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          {/* 状态筛选 */}
          <Select value={statusFilter} onValueChange={handleStatusFilterChange}>
            <SelectTrigger className="w-full sm:w-[140px]">
              <SelectValue placeholder="状态筛选" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem key="status-all" value="all">
                全部状态
              </SelectItem>
              <SelectItem key="status-0" value="0">
                正常
              </SelectItem>
              <SelectItem key="status-1" value="1">
                停用
              </SelectItem>
            </SelectContent>
          </Select>

          {/* 搜索框 */}
          <div className="relative w-full sm:w-64">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="搜索字典标签/编码..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && handleSearch(e)}
              className="pl-10 pr-10"
            />
            <Button
              variant="ghost"
              size="icon"
              className="absolute right-0 top-0 h-full w-10 p-0"
              onClick={handleSearch}
            >
              <Search className="w-4 h-4" />
              <span className="sr-only">搜索</span>
            </Button>
          </div>

          {/* 刷新按钮 */}
          <Button
            variant="outline"
            size="icon"
            onClick={loadDictData}
            disabled={isLoading}
          >
            <RefreshCw
              className={`w-4 h-4 ${isLoading ? "animate-spin" : ""}`}
            />
            <span className="sr-only">刷新</span>
          </Button>

          {/* 新增按钮 */}
          <Button onClick={handleAdd} disabled={dictTypes.length === 0}>
            <Plus className="w-4 h-4 mr-2" />
            新增字典数据
          </Button>
        </div>
      </div>

      {/* 表格区域 */}
      <div className="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>字典类型</TableHead>
              <TableHead>字典标签</TableHead>
              <TableHead>字典键值</TableHead>
              <TableHead>是否默认</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>创建时间</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableRow>
                <TableCell colSpan={9} className="h-40 text-center">
                  <div className="flex flex-col items-center">
                    <RefreshCw className="w-6 h-6 text-gray-400 animate-spin mb-2" />
                    <span className="text-gray-500">加载中...</span>
                  </div>
                </TableCell>
              </TableRow>
            ) : dictDataList.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} className="h-40 text-center">
                  <div className="flex flex-col items-center">
                    <AlertCircle className="w-6 h-6 text-gray-400 mb-2" />
                    <span className="text-gray-500">暂无符合条件的字典数据</span>
                    {dictTypes.length > 0 && (
                      <Button
                        variant="link"
                        onClick={handleAdd}
                        className="mt-1"
                      >
                        点击新增数据
                      </Button>
                    )}
                  </div>
                </TableCell>
              </TableRow>
            ) : (
              dictDataList.map((data) => (
                <TableRow
                  key={data.dictCode}
                  className="hover:bg-gray-50"
                >
                  <TableCell>
                    <div className="flex flex-col">
                      <span>{getDictTypeName(data.dictType)}</span>
                    </div>
                  </TableCell>
                  <TableCell>{data.dictLabel}</TableCell>
                  <TableCell>{data.dictValue}</TableCell>
                  <TableCell>{renderIsDefault(data.isDefault)}</TableCell>
                  <TableCell>{renderStatusBadge(data.status)}</TableCell>
                  <TableCell>
                    {data.createdDate
                      ? new Date(data.createdDate).toLocaleString()
                      : "-"}
                  </TableCell>

                  <TableCell className="text-right">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8">
                          <MoreHorizontal className="w-4 h-4" />
                          <span className="sr-only">操作</span>
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => handleEdit(data)}>
                          <Edit className="w-4 h-4 mr-2" />
                          编辑
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          onClick={() => handleDelete(data.dictCode)}
                          className="text-red-600 focus:text-red-600"
                        >
                          <Trash2 className="w-4 h-4 mr-2" />
                          删除
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 分页组件 */}
      {!isLoading && renderPagination()}

      {/* 新增/编辑模态框（已移除字典编码输入框） */}
      <Dialog open={isModalOpen} onOpenChange={() => setIsModalOpen(false)}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>
              {currentData ? "编辑字典数据" : "新增字典数据"}
            </DialogTitle>
            <DialogDescription>
              {currentData
                ? "修改字典数据的详细信息，带*为必填项"
                : "创建新的字典数据，带*为必填项"}
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            {/* 字典类型 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="dictType" className="text-right">
                字典类型 <span className="text-red-500">*</span>
              </Label>
              <Select
                value={formData.dictType}
                onValueChange={(value) => handleSelectChange("dictType", value)}
              >
                <SelectTrigger
                  className={`col-span-3 ${
                    formErrors.dictType ? "border-red-500" : ""
                  }`}
                >
                  <SelectValue placeholder="请选择字典类型" />
                </SelectTrigger>
                <SelectContent>
                  {dictTypes.map((type) => (
                    <SelectItem
                      key={`modal-type-${type.dictType}`}
                      value={type.dictType}
                    >
                      {type.dictName} 
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {formErrors.dictType && (
                <p className="col-span-3 col-start-2 text-sm text-red-500 mt-1">
                  {formErrors.dictType}
                </p>
              )}
            </div>

            {/* 字典标签 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="dictLabel" className="text-right">
                字典标签 <span className="text-red-500">*</span>
              </Label>
              <Input
                id="dictLabel"
                name="dictLabel"
                value={formData.dictLabel}
                onChange={handleInputChange}
                className={`col-span-3 ${
                  formErrors.dictLabel ? "border-red-500" : ""
                }`}
                placeholder="请输入显示用的字典标签"
              />
              {formErrors.dictLabel && (
                <p className="col-span-3 col-start-2 text-sm text-red-500 mt-1">
                  {formErrors.dictLabel}
                </p>
              )}
            </div>

            {/* 字典键值 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="dictValue" className="text-right">
                字典键值 <span className="text-red-500">*</span>
              </Label>
              <Input
                id="dictValue"
                name="dictValue"
                value={formData.dictValue}
                onChange={handleInputChange}
                className={`col-span-3 ${
                  formErrors.dictValue ? "border-red-500" : ""
                }`}
                placeholder="请输入实际存储的字典键值"
              />
              {formErrors.dictValue && (
                <p className="col-span-3 col-start-2 text-sm text-red-500 mt-1">
                  {formErrors.dictValue}
                </p>
              )}
            </div>

            {/* 是否默认 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="isDefault" className="text-right">
                是否默认
              </Label>
              <Select
                value={formData.isDefault}
                onValueChange={(value) =>
                  handleSelectChange("isDefault", value)
                }
              >
                <SelectTrigger className="col-span-3">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem key="default-0" value="0">
                    否
                  </SelectItem>
                  <SelectItem key="default-1" value="1">
                    是
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 状态 */}
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="status" className="text-right">
                状态
              </Label>
              <Select
                value={formData.status}
                onValueChange={(value) => handleSelectChange("status", value)}
              >
                <SelectTrigger className="col-span-3">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem key="modal-status-0" value="0">
                    正常
                  </SelectItem>
                  <SelectItem key="modal-status-1" value="1">
                    停用
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsModalOpen(false)}>
              取消
            </Button>
            <Button onClick={handleSubmit}>
              <Save className="w-4 h-4 mr-2" />
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default DictionaryDataManager;